import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/homeworks.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/models/common/assignmentState.dart';
import 'package:ichinesereader/models/student/AssignmentDetail.dart';
import 'package:ichinesereader/models/student/StudentMiniJson.dart';
import 'package:ichinesereader/models/teacher/AssignmentType.dart';
import 'package:ichinesereader/models/teacher/assignedBooks.dart';
import 'package:ichinesereader/pages/teacher/homeworkStepper.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/themes/buttonStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/addToFolderDialog.dart';
import 'package:ichinesereader/widgets/dialogs/chooseAssignmentBookType.dart';
import 'package:just_the_tooltip/just_the_tooltip.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class HomeworkDataGrids extends StatelessWidget {
  HomeworkDataGrids(this.isTeacher, this.assignmentItems);

  List<AssignmentDetail> assignmentItems;
  bool isTeacher = true;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final HomeworksController _assignmentsController = Get.find();
  final UserController _userController = Get.find();
  final BooksController _booksController = Get.find();
  AppButtonStyles _appButtonStyles = new AppButtonStyles();
  var box = Hive.box('appconfig');
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssignmentsDataGrids');
    final isMediumScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenMediumSize;
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Column(mainAxisAlignment: MainAxisAlignment.start, children: [
      isTeacher
          //IntrinsicHeight 元件导致 chips 和 button 上下空间过大
          ? IntrinsicHeight(
              ////////上方的一排按钮的背景////////////////
              child: isMediumScreen || isSmallScreen
                  ? Container(
                      padding: EdgeInsets.only(
                        left: 9.0,
                      ),
                      child: Column(
                        children: [
                          /////////////////彩色按钮///////////////////
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              ElevatedButton(
                                  style: _appButtonStyles.createButtonStyle(),
                                  //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                  child: Text(
                                    'Create'.tr,
                                    style: TextStyle(
                                      fontFamily: 'Montserrat',
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight,
                                      fontSize: 15,
                                    ),
                                  ),
                                  onPressed: () {
                                    showGeneralDialog(
                                        context: context,
                                        transitionDuration:
                                            Duration(milliseconds: 400),
                                        pageBuilder: (bc, ania, anis) {
                                          return ChooseAssignmentTypeDialog();
                                        });
                                  }),
                              Padding(
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 3.0),
                                child: ElevatedButton(
                                    style:
                                        _appButtonStyles.duplicateButtonStyle(),
                                    //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                    child: Text(
                                      'Duplicate'.tr,
                                      style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : AppTheme.colors.lightOrange,
                                        fontSize: 15,
                                        fontFamily: 'Montserrat',
                                      ),
                                    ),
                                    onPressed: () {
                                      if (this
                                              ._dataGridController
                                              .selectedRows
                                              .length >
                                          0) {
                                        var _selectedRow = this
                                            ._dataGridController
                                            .selectedRows[0];
                                        var assignmentId = _selectedRow
                                            .getCells()
                                            .where((element) =>
                                                element.columnName == 'Id')
                                            .first
                                            .value;
                                        var _assignment = _assignmentsController
                                            .assignmentItems
                                            .where((element) =>
                                                element.id == assignmentId)
                                            .first;
                                        List<BookItem> bookitems = [];

                                        if (_assignment.books != null) {
                                          AssignedBooks books =
                                              new AssignedBooks();
                                          books.assignedBooks = [];

                                          _assignment.books?.forEach((book) {
                                            BookItem item = new BookItem();
                                            item.bookId = book.bookId;
                                            item.bookCode = book.bookCode;
                                            item.audio = book.audio;
                                            item.bookContentLink =
                                                book.bookContentLink;
                                            item.bookImageLink =
                                                book.bookImageLink;
                                            item.bookTitle = book.bookTitle;
                                            bookitems.add(item);

                                            // AssignedBook item = new AssignedBook();
                                            // item.id = book.bookId;
                                            // item.title = book.bookTitle;
                                            // item.teacherAssessment = false;
                                          });
                                          Get.to(() => HomeworkSteps(
                                              isNew: false,
                                              books: bookitems,
                                              assignmentDetail: _assignment));
                                        }
                                      }
                                    }),
                              ),
                              Padding(
                                padding:
                                    const EdgeInsets.symmetric(horizontal: 3.0),
                                child: ElevatedButton(
                                    style: _appButtonStyles.deleteButtonStyle(),
                                    //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                    child: Text(
                                      'Delete'.tr,
                                      style: TextStyle(
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : AppTheme.colors.lightPink,
                                      ),
                                    ),
                                    onPressed: () {
                                      if (this
                                              ._dataGridController
                                              .selectedRows
                                              .length >
                                          0) {
                                        var _selectedRow = this
                                            ._dataGridController
                                            .selectedRows[0];
                                        var assignmentId = _selectedRow
                                            .getCells()
                                            .where((element) =>
                                                element.columnName == 'Id')
                                            .first
                                            .value;
                                        var isQueued = _selectedRow
                                                .getCells()
                                                .where((element) =>
                                                    element.columnName ==
                                                    'Status')
                                                .first
                                                .value
                                                .toString() ==
                                            'QUEUED';
                                        if (isQueued) {
                                          String classId = _userController
                                              .currentClass.value.classId
                                              .toString();
                                          _assignmentsController
                                              .deleteHomeworkByClassId(
                                                  classId, assignmentId)
                                              .then((statusMessage) {
                                            if (statusMessage.status == 1000) {
                                              showSnackMsg('Homework deleted!');
                                            } else {
                                              showSnackMsg(
                                                  'Failed to delete homework, please try again later!');
                                            }
                                          });
                                        } else {
                                          showSnackMsg(
                                              'Only queued homework can be deleted!');
                                        }
                                      }
                                    }),
                              ),
                              ElevatedButton(
                                  style: _appButtonStyles.addButtonStyle(),
                                  //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                  child: Text(
                                    'Add to Favorite'.tr,
                                    style: TextStyle(
                                        fontSize: 15.0,
                                        color: Get.isDarkMode
                                            ? Colors.black
                                            : Get.theme.primaryColorLight),
                                  ),
                                  onPressed: () {
                                    if (this
                                            ._dataGridController
                                            .selectedRows
                                            .length >
                                        0) {
                                      _booksController.fetchBookAllFolders();
                                      var _selectedRow = this
                                          ._dataGridController
                                          .selectedRows[0];
                                      var assignmentId = _selectedRow
                                          .getCells()
                                          .where((element) =>
                                              element.columnName == 'Id')
                                          .first
                                          .value;
                                      var _assignment = _assignmentsController
                                          .assignmentItems
                                          .where((element) =>
                                              element.id == assignmentId)
                                          .first;
                                      if (_assignment.books != null &&
                                          _assignment.books!.isNotEmpty) {
                                        List<String> _bookIds = [];
                                        _assignment.books?.forEach((book) {
                                          _bookIds.add(book.bookId.toString());
                                        });

                                        showGeneralDialog(
                                            context: context,
                                            transitionDuration:
                                                Duration(milliseconds: 400),
                                            pageBuilder: (bc, ania, anis) {
                                              return AddToFolderDialog(
                                                  readingType:
                                                      NanhaiBookReadingTypes
                                                          .favorite,
                                                  title: isTeacher
                                                      ? 'Add to Lesson Plan'.tr
                                                      : 'Add to Folder'.tr,
                                                  selected: _bookIds,
                                                  message: '',
                                                  readingTypeFrom: '');
                                            });
                                      }
                                    }
                                  }),
                            ],
                          ),
                          //////////椭圆形选项//////////
                          FormBuilderChoiceChip(
                            alignment: WrapAlignment.end,
                            decoration: InputDecoration(
                              border: InputBorder.none,
                            ),
                            spacing: 3.0,
                            backgroundColor: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.grey,
                            // selectedColor:
                            //     Theme.of(context).primaryColorDark,
                            selectedColor: Get.isDarkMode
                                ? Colors.white
                                : AppTheme.colors.orangeBtn,

                            name: 'assignment_state_chip',
                            onChanged: (value) {
                              if (value == null) return;

                              AssignmentType dto = new AssignmentType();
                              dto.live = false;
                              dto.past = false;
                              dto.queued = false;
                              dto.assignmentType = 'ASSIGNMENT';
                              var item = value as AssignmentState;
                              if (item.value == 'live') dto.live = true;
                              if (item.value == 'past') dto.past = true;
                              if (item.value == 'queued') dto.queued = true;

                              String _classId = box.get(
                                      CacheManagerKey['currentclass']
                                          .toString()) ??
                                  '';

                              if (_classId != '')
                                _assignmentsController.fetchTeacherHomworks(
                                    _classId, dto);
                            },
                            initialValue:
                                AssignmentState(value: 'live', label: 'OPEN'),
                            options: Constants.assignmentStateOptions
                                .map((state) =>
                                    FormBuilderChipOption<AssignmentState>(
                                      value: state,
                                      child: Text(
                                        state.label.toString().tr,
                                        style: TextStyle(
                                            fontSize: 13.0,
                                            color: Get.isDarkMode
                                                ? Colors.black
                                                : AppTheme.colors.lightOrange),
                                      ),
                                    ))
                                .toList(),
                          ),
                        ],
                      ),
                    )
                  : Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        //////////椭圆形选项//////////
                        Expanded(
                          child: FormBuilderChoiceChip(
                            decoration: InputDecoration.collapsed(
                              hintText: '',
                              border: InputBorder.none,
                            ),
                            spacing: 3.0,
                            backgroundColor: Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.grey,
                            selectedColor: Get.isDarkMode
                                ? Theme.of(context).primaryColorDark
                                : AppTheme.colors.orangeBtn,
                            name: 'assignment_state_chip',
                            onChanged: (value) {
                              if (value == null) return;

                              AssignmentType dto = new AssignmentType();
                              dto.live = false;
                              dto.past = false;
                              dto.queued = false;
                              dto.assignmentType = 'ASSIGNMENT';
                              var item = value as AssignmentState;
                              if (item.value == 'live') dto.live = true;
                              if (item.value == 'past') dto.past = true;
                              if (item.value == 'queued') dto.queued = true;

                              String _classId = box.get(
                                      CacheManagerKey['currentclass']
                                          .toString()) ??
                                  '';

                              if (_classId != '')
                                _assignmentsController.fetchTeacherHomworks(
                                    _classId, dto);
                            },
                            initialValue:
                                AssignmentState(value: 'live', label: 'OPEN'),
                            options: Constants.assignmentStateOptions
                                .map((state) =>
                                    FormBuilderChipOption<AssignmentState>(
                                      value: state,
                                      child: Text(
                                        state.label.toString().tr,
                                        style: TextStyle(
                                            color: Get.isDarkMode
                                                ? Colors.black
                                                : AppTheme.colors.lightOrange),
                                      ),
                                    ))
                                .toList(),
                          ),
                        ),
                        /////////////////彩色按钮///////////////////
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            ElevatedButton(
                                style: _appButtonStyles.createButtonStyle(),
                                //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                child: Text(
                                  'Create'.tr,
                                  style: TextStyle(
                                    color: Get.isDarkMode
                                        ? Colors.black
                                        : Get.theme.primaryColorLight,
                                  ),
                                ),
                                onPressed: () {
                                  showGeneralDialog(
                                      context: context,
                                      transitionDuration:
                                          Duration(milliseconds: 400),
                                      pageBuilder: (bc, ania, anis) {
                                        return ChooseAssignmentTypeDialog();
                                      });
                                }),
                            Padding(
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 9.0),
                              child: ElevatedButton(
                                  style:
                                      _appButtonStyles.duplicateButtonStyle(),
                                  //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                  child: Text(
                                    'Duplicate'.tr,
                                    style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight,
                                    ),
                                  ),
                                  onPressed: () {
                                    if (this
                                            ._dataGridController
                                            .selectedRows
                                            .length >
                                        0) {
                                      var _selectedRow = this
                                          ._dataGridController
                                          .selectedRows[0];
                                      var assignmentId = _selectedRow
                                          .getCells()
                                          .where((element) =>
                                              element.columnName == 'Id')
                                          .first
                                          .value;
                                      var _assignment = _assignmentsController
                                          .assignmentItems
                                          .where((element) =>
                                              element.id == assignmentId)
                                          .first;
                                      List<BookItem> bookitems = [];

                                      if (_assignment.books != null) {
                                        AssignedBooks books =
                                            new AssignedBooks();
                                        books.assignedBooks = [];

                                        _assignment.books?.forEach((book) {
                                          BookItem item = new BookItem();
                                          item.bookId = book.bookId;
                                          item.bookCode = book.bookCode;
                                          item.audio = book.audio;
                                          item.bookContentLink =
                                              book.bookContentLink;
                                          item.bookImageLink =
                                              book.bookImageLink;
                                          item.bookTitle = book.bookTitle;
                                          bookitems.add(item);

                                          // AssignedBook item = new AssignedBook();
                                          // item.id = book.bookId;
                                          // item.title = book.bookTitle;
                                          // item.teacherAssessment = false;
                                        });
                                        Get.to(() => HomeworkSteps(
                                            isNew: false,
                                            books: bookitems,
                                            assignmentDetail: _assignment));
                                      }
                                    }
                                  }),
                            ),
                            Padding(
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 9.0),
                              child: ElevatedButton(
                                  style: _appButtonStyles.deleteButtonStyle(),
                                  //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                  child: Text(
                                    'Delete'.tr,
                                    style: TextStyle(
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : AppTheme.colors.lightPink,
                                    ),
                                  ),
                                  onPressed: () {
                                    if (this
                                            ._dataGridController
                                            .selectedRows
                                            .length >
                                        0) {
                                      var _selectedRow = this
                                          ._dataGridController
                                          .selectedRows[0];
                                      var assignmentId = _selectedRow
                                          .getCells()
                                          .where((element) =>
                                              element.columnName == 'Id')
                                          .first
                                          .value;
                                      var isQueued = _selectedRow
                                              .getCells()
                                              .where((element) =>
                                                  element.columnName ==
                                                  'Status')
                                              .first
                                              .value
                                              .toString() ==
                                          'QUEUED';
                                      if (isQueued) {
                                        String _classId = box.get(
                                                CacheManagerKey['currentclass']
                                                    .toString()) ??
                                            '';
                                        _assignmentsController
                                            .deleteHomeworkByClassId(
                                                _classId, assignmentId)
                                            .then((statusMessage) {
                                          if (statusMessage.status == 1000) {
                                            showSnackMsg('Homework deleted!');
                                          } else {
                                            showSnackMsg(
                                                'Failed to delete homework, please try again later!');
                                          }
                                        });
                                      } else {
                                        showSnackMsg(
                                            'Only queued homework can be deleted!');
                                      }
                                    }
                                  }),
                            ),
                            ElevatedButton(
                                style: _appButtonStyles.addButtonStyle(),
                                //_appButtonStyles 目前只改变ElevatedButton()的Style, 没改变Text()的Style
                                child: Text(
                                  'Add to Favorite'.tr,
                                  style: TextStyle(
                                      fontSize: 15.0,
                                      color: Get.isDarkMode
                                          ? Colors.black
                                          : Get.theme.primaryColorLight),
                                ),
                                onPressed: () {
                                  if (this
                                          ._dataGridController
                                          .selectedRows
                                          .length >
                                      0) {
                                    _booksController.fetchBookAllFolders();
                                    var _selectedRow = this
                                        ._dataGridController
                                        .selectedRows[0];
                                    var assignmentId = _selectedRow
                                        .getCells()
                                        .where((element) =>
                                            element.columnName == 'Id')
                                        .first
                                        .value;
                                    var _assignment = _assignmentsController
                                        .assignmentItems
                                        .where((element) =>
                                            element.id == assignmentId)
                                        .first;
                                    if (_assignment.books != null &&
                                        _assignment.books!.isNotEmpty) {
                                      List<String> _bookIds = [];
                                      _assignment.books?.forEach((book) {
                                        _bookIds.add(book.bookId.toString());
                                      });

                                      showGeneralDialog(
                                          context: context,
                                          transitionDuration:
                                              Duration(milliseconds: 400),
                                          pageBuilder: (bc, ania, anis) {
                                            return AddToFolderDialog(
                                                readingType:
                                                    NanhaiBookReadingTypes
                                                        .favorite,
                                                title: isTeacher
                                                    ? 'Add to Lesson Plan'.tr
                                                    : 'Add to Folder'.tr,
                                                selected: _bookIds,
                                                message: '',
                                                readingTypeFrom: '');
                                          });
                                    }
                                  }
                                }),
                          ],
                        ),
                      ],
                    ),
            )
          : Visibility(
              visible: false,
              child: Text(''),
            ),
      Expanded(child: _buildDataGrid()),
      //_buildDataGrid(),
    ]);
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: AssignmentDataGridSource(
              items: assignmentItems, isTeacher: isTeacher),
          isScrollbarAlwaysShown: true,
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          showCheckboxColumn: isTeacher ? true : false,
          allowFiltering: true,
          checkboxColumnSettings: Get.isDarkMode
              ? DataGridCheckboxColumnSettings(
                  backgroundColor: Color(0xff0a0e21),
                )
              : DataGridCheckboxColumnSettings(
                  backgroundColor: Colors.blue[50]),
          allowSorting: true,
          allowTriStateSorting: true,
          allowSwiping: false,
          controller: _dataGridController,
          selectionMode:
              isTeacher ? SelectionMode.multiple : SelectionMode.none,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {},
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
                width: 240,
                columnName: 'Task',
                label: buildDataGridColumnLabel('Task')),
            GridColumn(
                columnName: 'Status',
                //allowFiltering: false,
                width: isWebOrDesktop ? 140 : 140,
                label: buildDataGridColumnLabel('Status')),
            GridColumn(
                columnName: 'RequiredReadings',
                width: isWebOrDesktop ? 190.0 : 190.0,
                allowFiltering: false,
                label: buildDataGridColumnLabel('RequiredReadings')),
            GridColumn(
              columnName: 'Audio',
              allowFiltering: false,
              width: isWebOrDesktop ? 120.0 : 120.0,
              label: buildDataGridColumnLabel('Audio'),
            ),
            GridColumn(
              columnName: 'Text',
              allowFiltering: false,
              width: isWebOrDesktop ? 120.0 : 120.0,
              label: buildDataGridColumnLabel('Text'),
            ),
            GridColumn(
              columnName: 'StartDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('StartDate'),
            ),
            GridColumn(
              columnName: 'DueDate',
              allowFiltering: false,
              width: 160,
              label: buildDataGridColumnLabel('DueDate'),
            ),
            GridColumn(
              columnName: 'Students',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Students'),
            ),
            GridColumn(
              columnName: 'Id',
              allowFiltering: false,
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource(
      {required List<AssignmentDetail> items, required this.isTeacher}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'Task', value: dataGridRow.name),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.status?.toUpperCase()),
              // DataGridCell<int>(
              //     columnName: 'FinishedStudents',
              //     value: dataGridRow.completedStudents),
              // DataGridCell<int>(
              //     columnName: 'RequiredStudents',
              //     value: dataGridRow.studentUserNames?.length ?? 0),
              DataGridCell<String>(
                  columnName: 'RequiredReadings',
                  value:
                      '${dataGridRow.noOfBookToBeRead.toString()}/${dataGridRow.numBooks.toString()}'),
              DataGridCell<String>(
                  columnName: 'Audio', value: dataGridRow.settings?.lang),
              DataGridCell<String>(
                  columnName: 'Text', value: dataGridRow.settings?.language),
              // DataGridCell<int>(
              //   columnName: 'CreateDate',
              //   value: dataGridRow.createDate,
              // ),
              DataGridCell<int>(
                columnName: 'StartDate',
                value: dataGridRow.startDate,
              ),
              DataGridCell<int>(
                columnName: 'DueDate',
                value: dataGridRow.endDateUtc,
              ),
              DataGridCell<List<StudentMiniJson>>(
                  columnName: 'Students',
                  value: dataGridRow.studentMiniJsoNs ?? <StudentMiniJson>[]),
              DataGridCell<String>(columnName: 'Id', value: dataGridRow.id),
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];
  bool isTeacher = true;
  HomeworksController _assignmentsController = Get.find();

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    String studentNames = '';
    List<StudentMiniJson> students = row
        .getCells()
        .where((element) => element.columnName == 'Students')
        .first
        .value;
    if (students.isNotEmpty) {
      students.forEach((s) {
        studentNames = studentNames +
            s.lastName.toString() +
            ' ' +
            s.firstName.toString() +
            ', ';
      });

      if (studentNames.length > 2) {
        studentNames = studentNames.substring(0, studentNames.length - 2);
      }
    }

    //BooksController _booksController = Get.find();
    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'CreateDate' ||
              dataGridCell.columnName == 'StartDate' ||
              dataGridCell.columnName == 'DueDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 6.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    ' - ',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            String _status = dataGridCell.value
                .toString()
                .replaceAll('LIVE', 'OPEN')
                .replaceAll('PAST', 'CLOSED')
                .replaceAll('COMPLETED', 'CLOSED');
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 6.0),
              child: Text(
                _status,
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == 'Task') {
            return Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 6.0),
              child: GestureDetector(
                onTap: () {
                  if (isTeacher) {
                    var assignmentId = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    var _assignment = _assignmentsController.assignmentItems
                        .where((element) => element.id == assignmentId)
                        .first;
                    List<BookItem> bookitems = [];

                    if (_assignment.books != null) {
                      AssignedBooks books = new AssignedBooks();
                      books.assignedBooks = [];

                      _assignment.books?.forEach((book) {
                        BookItem item = new BookItem();
                        item.bookId = book.bookId;
                        item.bookCode = book.bookCode;
                        item.audio = book.audio;
                        item.bookContentLink = book.bookContentLink;
                        item.bookImageLink = book.bookImageLink;
                        item.bookTitle = book.bookTitle;
                        bookitems.add(item);
                        // _booksController.addToSelectedBookItems(
                        //     item, NanhaiBookReadingTypes.library);
                      });
                      Get.to(() => HomeworkSteps(
                          isNew: false,
                          books: bookitems,
                          assignmentDetail: _assignment,
                          assignmentId: assignmentId,
                          from: 'edit'));
                    }
                  }
                },
                child: isTeacher
                    ? JustTheTooltip(
                        backgroundColor: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Get.theme.primaryColorLight,
                        preferredDirection: AxisDirection.right,
                        elevation: 4.0,
                        content: Container(
                          padding: EdgeInsets.all(8.0),
                          width: 480,
                          color: Colors.transparent,
                          child: Text(
                            studentNames,
                            style: TextStyle(
                              fontSize: 12,
                              color: Get.isDarkMode
                                  ? Colors.black
                                  : Colors.black87,
                            ),
                          ),
                        ),
                        child: Text(
                          dataGridCell.value.toString(),
                          style: Get.theme.textTheme.titleLarge,
                          overflow: TextOverflow.ellipsis,
                        ),
                      )
                    : Text(
                        dataGridCell.value.toString(),
                        style: Get.theme.textTheme.titleLarge,
                        overflow: TextOverflow.ellipsis,
                      ),
              ),
            );
          } else {
            return Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 6.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
